﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

namespace Golf.WebUI
{
    public partial class Checkout : System.Web.UI.Page
    {
        Golf.BLL.Golf_UserData userServer = new BLL.Golf_UserData();
        Golf.BLL.Golf_User us = new BLL.Golf_User();
        Golf.Model.Golf_User Golf_User_Model = new Model.Golf_User();
        /// <summary>
        /// 地址
        /// </summary>
        public string CursMsg = "";
        /// <summary>
        /// 国家
        /// </summary>
        public string _country = "China";
        /// <summary>
        /// 邮箱
        /// </summary>
        public string Customer_Email;
        /// <summary>
        /// 登陆  或者 注册用户的id
        /// </summary>
        public int UserId = -1;
        /// <summary>
        /// 送货地址id
        /// </summary>
        public int AddressId = 0;
        /// <summary>
        /// 用户 性别
        /// </summary>
        public int sex = 0;
        /// <summary>
        ///判断是否是注册会员
        /// </summary>
        public int UT = 1;//默认为 1  就是 打开的时候 不进行验证
        /// <summary>
        /// 给客户下订单
        /// </summary>
        public string _Email = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                switch (Request.Form["action"])
                {
                    case "checkout"://注册
                        Registration();
                        break;
                    case "Modify":
                        _Modify();
                        break;
                    case "Valid_email":
                        CheckEmail(Request.Form["email"].ToString());
                        break;
                    case "order_sub":
                        Get_urlMsg();
                        break;
                    case "get_Coupon":
                        get_Coupon();
                        break;
                }
                Object obj = CookiesHelper.GetCookie("_Customer_id");
                if (obj == null || obj.ToString() == "")
                {
                }
                else
                {
                    UserId = int.Parse(obj.ToString());
                }
                BadinMessage(UserId);
            }
            //就放在外面 吧    下单的时候 需要商品id和属性id哟
            getbind();
        }
        #region  获取优惠劵 金额 和信息

        /// <summary>
        /// 获取优惠劵
        /// </summary>
        private void get_Coupon()
        {
            string Cert_Code = Server.UrlDecode(Request.Form["Code_Coupon"]);

            Golf.BLL.Golf_Coupons bll = new Golf.BLL.Golf_Coupons();
            if (Cert_Code == "")
            {
                Response.Write("0|请输入Code|");
                return;
            }
            List<Golf.Model.Golf_Coupons> list = bll.GetModelList("CouponsNumber='" + Cert_Code + "'");
            foreach (var item in list)
            {
                if (item.IsRestriction)
                {
                    Response.Write("0|已经限制使用|");
                    return;
                }
                else
                {
                    Response.Write(item.CouponsFacevalue + "|可以使用|");
                    return;
                }
            }
            Response.Write("0|没有找到|");
        }
        /// <summary>
        /// 优惠劵代码
        /// </summary>
        /// <param name="Coupons_Code"></param>
        private decimal get_Coupon(string Coupons_Code)
        {
            Golf.BLL.Golf_Coupons bll = new Golf.BLL.Golf_Coupons();
            List<Golf.Model.Golf_Coupons> list = bll.GetModelList("CouponsNumber='" + Coupons_Code + "'");
            decimal money = 0;
            foreach (var item in list)
            {
                money = item.CouponsFacevalue;
            }
            return money;
        }
        #endregion

        #region  客户  Golf_User  Golf_UserData Golf_Address
        /// <summary>
        /// 修改
        /// </summary>
        private void _Modify()
        {
            Golf.Model.Golf_UserData userdata = new Golf.Model.Golf_UserData();
            int sex = int.Parse(Server.UrlDecode(Request.Form["sex"]));
            string fristname = Server.UrlDecode(Request.Form["firstname"]);
            string lastname = Server.UrlDecode(Request.Form["lastname"]);
            string address = Server.UrlDecode(Request.Form["street_address"]); //this.street_address.Value;
            string city = Server.UrlDecode(Request.Form["city"]); //this.city.Value;
            string province = Server.UrlDecode(Request.Form["state"]); //this.state.Value;
            string email_address = Server.UrlDecode(Request.Form["email_address"]); //邮编this.email_address.Value;
            string tel = Server.UrlDecode(Request.Form["telephone"]); //this.telephone.Value;
            string postcode = Server.UrlDecode(Request.Form["postcode"]);
            string country = Server.UrlDecode(Request.Form["_country"]);//国家
            int number = int.Parse(Server.UrlDecode(Request.Form["number"]));//修改的用户id
            int address_Id = int.Parse(Server.UrlDecode(Request.Form["addressId"]));//修改的用户  送货地址id
            UT = int.Parse(Server.UrlDecode(Request.Form["UT"]));//判断是为会员   0为会员  
            UserId = number;
            Golf.Model.Golf_User user = us.GetModel(number);
            if (user == null)
            {//如果没有找到用户 就添加一个
                Registration();
                return;
            }
            else
            {
                if (user.UserType == 0)//会员就只修改 address 表中的数据了
                {
                    _Modify_reg(address_Id, number);
                    return;
                }
            }
            //匿名用户 获取的登陆状态 (用户信息表)
            user.Id = number;
            user.FristName = fristname;//姓名
            user.LastName = lastname;// last
            user.Email = email_address;//邮箱地址  
            if (us.Update(user))
            {
                _Login(number);
                userdata = null;
                List<Golf.Model.Golf_UserData> list = userServer.GetModelList("UserId=" + number);
                foreach (var item in list)
                {
                    userdata = item;
                }
                userdata.sex = sex;
                userdata.FristName = fristname;
                userdata.LastName = lastname;
                userdata.Address = address;
                userdata.PostCode = postcode;
                userdata.Province = country;//国家
                userdata.City = city;//省
                userdata.Borough = province;//市
                userdata.Tel = tel;
                userServer.Update(userdata);

                //修改数据岛 golf_address表中去
                Golf.BLL.Golf_Address bll_address = new Golf.BLL.Golf_Address();
                Golf.Model.Golf_Address golf_address = bll_address.GetModel(address_Id);
                golf_address.UserId = number;
                golf_address.FristName = fristname + " " + lastname;
                golf_address.LastName = sex.ToString();//数据库中没哟sex字段
                golf_address.ConsigneeFrist = fristname;//所活人姓
                golf_address.ConsigneeLast = lastname;//收货人名
                golf_address.Mobile = tel;
                golf_address.Tel = tel;

                golf_address.PostCode = postcode;
                golf_address.Address = address;
                golf_address.Email = email_address;
                golf_address.FitDeliveryTime = 0;
                golf_address.Province = country;
                golf_address.City = city;
                golf_address.Borough = province;
                golf_address.IsShow = true;
                if (bll_address.Update(golf_address))
                {
                    Response.Write(number + "|" + golf_address.Id + "|");//返回 会员id 和地址id
                }
                else
                {
                    Response.Write(number + "|-1|");//返回 会员id 和地址id
                }
            }
            else
            {
                Response.Write(number + "|-1|");//返回 会员id 和地址id
            }
        }
        /// <summary>
        /// 注册
        /// </summary>
        public void Registration()
        {
            Golf.Model.Golf_UserData userdata = new Golf.Model.Golf_UserData();
            Golf.Model.Golf_User user = new Model.Golf_User();
            Golf.Model.Golf_Address golf_address = new Model.Golf_Address();
            int sex = int.Parse(Server.UrlDecode(Request.Form["sex"]));
            string fristname = Server.UrlDecode(Request.Form["firstname"]);
            string lastname = Server.UrlDecode(Request.Form["lastname"]);
            string address = Server.UrlDecode(Request.Form["street_address"]); //this.street_address.Value;
            string city = Server.UrlDecode(Request.Form["city"]); //this.city.Value;
            string province = Server.UrlDecode(Request.Form["state"]); //this.state.Value;
            string email_address = Server.UrlDecode(Request.Form["email_address"]); //邮编this.email_address.Value;
            string tel = Server.UrlDecode(Request.Form["telephone"]); //this.telephone.Value;

            string postcode = Server.UrlDecode(Request.Form["postcode"]);
            string country = Server.UrlDecode(Request.Form["_country"]);//国家
            userdata.sex = sex;
            userdata.FristName = fristname;
            userdata.LastName = lastname;
            userdata.Address = address;
            userdata.PostCode = postcode;
            userdata.Province = country;//国家
            userdata.City = city;//省
            userdata.Borough = province;//市

            userdata.Tel = tel;
            //没有国家名
            // = this.country.SelectedIndex.ToString() ;
            //匿名用户 获取的登陆状态 (用户信息表)
            user.UserType = 1;//来源  非注册用户
            user.State = 0;
            user.FristName = fristname;//姓名
            user.LastName = lastname;//
            user.PassWord = "Golf";//默认密码
            user.Email = email_address;//邮箱地址
            user.LoginTime = DateTime.Now;
            user.RegisterTime = DateTime.Now;
            int number = us.Add(user);
            UserId = number;
            if (number != 0)
            {
                _Login(number);
                userdata.UserId = number;
                userServer.Add(userdata);

                //插入数据岛 golf_address表中去
                golf_address.UserId = number;
                golf_address.FristName = fristname + " " + lastname;
                golf_address.LastName = sex.ToString();//数据库中没哟sex字段  直接替换LastName
                golf_address.ConsigneeFrist = fristname;//所活人姓
                golf_address.ConsigneeLast = lastname;//收货人名
                golf_address.Mobile = tel;
                golf_address.Tel = tel;

                golf_address.PostCode = postcode;
                golf_address.Address = address;
                golf_address.Email = email_address;
                golf_address.FitDeliveryTime = 0;
                golf_address.Province = country;
                golf_address.City = city;
                golf_address.Borough = province;
                golf_address.CreateTime = DateTime.Now;
                golf_address.IsShow = true;
                Golf.BLL.Golf_Address bll_address = new Golf.BLL.Golf_Address();
                int addressId = bll_address.Add(golf_address);
                Response.Write(number + "|" + addressId + "|");//返回 会员id 和地址id
            }
            else
            {
                Response.Write("-1|-1|");//返回 会员id 和地址id
            }
        }


        /// <summary>
        /// 修改会员的其中的一项收货地址
        /// </summary>
        /// <param name="red_address_id">会员地址id</param>
        /// <param name="red_user_id">会员id</param>
        private void _Modify_reg(int red_address_id, int red_user_id)
        {
            int sex = int.Parse(Server.UrlDecode(Request.Form["sex"]));
            string fristname = Server.UrlDecode(Request.Form["firstname"]);
            string lastname = Server.UrlDecode(Request.Form["lastname"]);
            string address = Server.UrlDecode(Request.Form["street_address"]); //this.street_address.Value;
            string city = Server.UrlDecode(Request.Form["city"]); //this.city.Value;
            string province = Server.UrlDecode(Request.Form["state"]); //this.state.Value;
            string email_address = Server.UrlDecode(Request.Form["email_address"]); //邮编this.email_address.Value;
            string tel = Server.UrlDecode(Request.Form["telephone"]); //this.telephone.Value;
            string postcode = Server.UrlDecode(Request.Form["postcode"]);
            string country = Server.UrlDecode(Request.Form["_country"]);//国家
            //修改数据岛 golf_address表中去
            Golf.BLL.Golf_Address bll_address = new Golf.BLL.Golf_Address();
            Golf.Model.Golf_Address golf_address = bll_address.GetModel(red_address_id);
            golf_address.FristName = fristname + " " + lastname;
            golf_address.LastName = sex.ToString();//数据库中没哟sex字段
            golf_address.ConsigneeFrist = fristname;//所活人姓
            golf_address.ConsigneeLast = lastname;//收货人名
            golf_address.Mobile = tel;
            golf_address.Tel = tel;
            golf_address.PostCode = postcode;
            golf_address.Address = address;
            golf_address.Email = email_address;
            golf_address.FitDeliveryTime = 0;
            golf_address.Province = country;
            golf_address.City = city;
            golf_address.Borough = province;
            golf_address.IsShow = true;
            if (bll_address.Update(golf_address))
            {
                Response.Write(red_user_id + "|" + red_address_id + "|");//返回 会员id 和地址id
            }

            else
            {
                Response.Write(red_user_id + "|-1|");//返回 会员id 和地址id
            }
        }
        #endregion


        #region  绑定 客户地址信息
        /// <summary>
        /// 绑定 客户地址信息
        /// </summary>
        /// <param name="id"></param>
        public void BadinMessage(int id)
        {
            Golf.Model.Golf_User user = null;
            user = us.GetModel(id);
            if (user == null) return;
            UT = user.UserType;
            if (user.UserType == 1)
            {
                Golf.BLL.Golf_Address addressBLl = new Golf.BLL.Golf_Address();
                List<Golf.Model.Golf_Address> address = addressBLl.GetModelList("UserId=" + id);
                foreach (var item in address)
                {
                    address_id.Value = item.Id.ToString();
                }
            }
            Golf.Model.Golf_UserData userdata = new Golf.Model.Golf_UserData();
            userdata = null;
            List<Golf.Model.Golf_UserData> list = userServer.GetModelList("UserId=" + id);
            foreach (var item in list)
            {
                userdata = item;
            }
            if (userdata == null) return;
            //绑定值到页面
            firstname.Value = userdata.FristName;
            lastname.Value = userdata.LastName;
            street_address.Value = userdata.Address;
            postcode.Value = userdata.PostCode;
            _country = userdata.Province;//g国家
            state.Value = userdata.City;///省
            city.Value = userdata.Borough;//市 
            Object bojEmail = CookiesHelper.GetCookie("_Customer_Email");
            if (bojEmail != null && bojEmail.ToString() != "")
            {  //存值
                Customer_Email = Server.UrlDecode(bojEmail.ToString());
            }
            telephone.Value = userdata.Tel;
            sex = (int)userdata.sex;
            User_Id.Value = userdata.UserId + "";
            // var CursMsg = firstname + " " + lastname + "<br/>" + street_address + "<br/>" + city + " " + postcode + "<br/>" + state + "," + _country;
            CursMsg = userdata.FristName + " " + userdata.LastName + "<br/>" + userdata.Address + "<br/>" + userdata.Borough + " " + userdata.PostCode + "<br/>" + userdata.City + "," + userdata.Province;

        }

        #endregion

        #region  验证邮箱的方法
        /// <summary>
        /// 验证邮箱的方法
        /// </summary>
        /// <param name="Email">条件邮箱</param>
        public void CheckEmail(string Email)
        {
            List<Golf.Model.Golf_User> list = us.DataTableToList(us.GetList(" Email like '%" + Email + "%' and  UserType=0").Tables[0]);
            foreach (var item in list)
            {
                if (Request.Form["email"].ToLower() == item.Email.ToLower())
                {
                    Response.Write("no|");
                }
            }
            if (list.Count == 0)
            {
                Response.Write("yes|");
            }
        }

        #endregion


        #region   加载购物车
        public DataTable dt = new DataTable();
        public string[] nums = null, pros = null;
        public int CookieCount = 0;
        /// <summary>
        /// 商品id
        /// </summary>
        public string _str1 = "";
        /// <summary>
        /// 商品数量
        /// </summary>
        public string _str2 = "";
        /// <summary>
        ///订单总额
        /// </summary>
        public string pro_price = "";
        Golf.BLL.Golf_Product bllproduct = new Golf.BLL.Golf_Product();
        /// <summary>
        /// 属性 拼接
        /// </summary>
        public string _str3 = "";
        /// <summary>
        /// 属性
        /// </summary>
        public string[] _attr;
        /// <summary>
        /// 键值
        /// </summary>
        public string[] _key;
        /// <summary>
        /// 加入到订单中的属性id,id|id,id|id
        /// </summary>
        public string _str4 = "";
        /// <summary>
        /// 订单 商品总数
        /// </summary>
        public int _sumCount = 0;
        /// <summary>
        /// 加载购物车
        /// </summary>
        public void getbind()
        {
            _str1 = null;
            _str2 = null;
            _str3 = null;
            _str4 = null;
            _key = null;
            pros = null;
            nums = null;
            _attr = null;
            if (Request.Cookies["GOLF"] != null && Request.Cookies["GOLF"].ToString() != "")
            {
                HttpCookie ShopCart = Request.Cookies["GOLF"];
                _key = ShopCart.Values.AllKeys;
                CookieCount = ShopCart.Values.Count;
                for (int i = 0; i < CookieCount; i++)
                {
                    if (ShopCart.Values[i] == null || ShopCart.Values[i].Trim() == "")
                    {
                        CookieCount = 0;
                        continue;
                    }
                    else
                    {
                        string[] Products = ShopCart.Values[i].Split('|');
                        if (Products.Length > 1)
                        {
                            _str1 += Products[0] + ",";
                            _str2 += Products[1] + ",";
                            _str3 += Products[2] + ",";
                            _str4 += Products[2] + "|";
                        }
                    }
                }
                if (_str1.Length > 1 & _str2.Length > 1)
                {
                    if (_str1.Substring(_str1.Length - 1, 1) == ",")
                        _str1 = _str1.Substring(0, _str1.Length - 1);
                    if (_str2.Substring(_str2.Length - 1, 1) == ",")
                        _str2 = _str2.Substring(0, _str2.Length - 1);
                    if (_str3.Substring(_str3.Length - 1, 1) == ",")
                        _str3 = _str3.Substring(0, _str3.Length - 1);

                    pros = _str1.Split(new char[] { ',' });
                    nums = _str2.Split(new char[] { ',' });
                    _attr = _str3.Split(new char[] { ',' });
                    //构建表格
                    DataTable _page_dt = new DataTable();
                    _page_dt = bllproduct.GetList("Id in(" + _str1 + ")").Tables[0];//获取商品的详细
                    _page_dt.Columns.Add("_attr", typeof(string));//添加属性列
                    _page_dt.Columns.Add("_Key", typeof(string));//添加cookie Key列  
                    dt.Columns.Add("Id", typeof(string));
                    dt.Columns.Add("Pro_Name", typeof(string));
                    dt.Columns.Add("Pro_Price", typeof(string));
                    dt.Columns.Add("Pro_Picture", typeof(string));
                    dt.Columns.Add("Pro_MarketPrice", typeof(string));
                    dt.Columns.Add("Pro_PromotionPrice", typeof(string));
                    dt.Columns.Add("_attr", typeof(string));//添加属性列
                    dt.Columns.Add("_Key", typeof(string));//添加cookie Key列 
                    decimal dSum1 = 0.00M, price1 = 0.00M;
                    for (int i = 0; i < _page_dt.Rows.Count; i++)
                    {
                        price1 = decimal.Parse(_page_dt.Rows[i]["Pro_Price"].ToString());
                        DataRow dr = _page_dt.Rows[i];
                        //循环匹配 商品
                        for (int j = 0; j < pros.Length; j++)
                        {
                            int num = int.Parse(nums[j]);
                            dSum1 += price1 * num;
                            DataRow dr1 = dt.NewRow();
                            if (pros[j] == dr["Id"].ToString())
                            {
                                dr1["_attr"] = Server.UrlDecode(_attr[j]);//添加该商品的属性
                                dr1["_Key"] = ShopCart.Values.AllKeys[j];//添加该商品的键值 
                                dr1["Id"] = _page_dt.Rows[i]["Id"].ToString();
                                dr1["Pro_Name"] = _page_dt.Rows[i]["Pro_Name"].ToString();
                                dr1["Pro_Price"] = _page_dt.Rows[i]["Pro_Price"].ToString();
                                dr1["Pro_Picture"] = _page_dt.Rows[i]["Pro_Picture"].ToString();
                                dr1["Pro_MarketPrice"] = _page_dt.Rows[i]["Pro_MarketPrice"].ToString();
                                dr1["Pro_PromotionPrice"] = _page_dt.Rows[i]["Pro_PromotionPrice"].ToString();
                                dt.Rows.Add(dr1);
                            }
                        }
                    }
                    pro_price = dSum1.ToString("0.00");
                    //总金额
                    this.ActualPrice.InnerHtml = "$" + dSum1.ToString("0.00");
                    dt.Dispose();
                }
            }
        }

        /// <summary>
        /// 获取数量
        /// </summary>
        public string getProNum(string proId)
        {
            string _strBack = "1";
            for (int i = 0; i < pros.Length; i++)
            {
                if (_key[i] == proId)
                {
                    _strBack = nums[i];
                }
            }
            return _strBack;
        }

        /// <summary>
        /// 小计金额
        /// </summary>
        public string getProPrice(string price, string proNums)
        {
            decimal _totle = 0.00M;
            _totle = decimal.Parse(price) * decimal.Parse(proNums);
            return _totle.ToString("0.00");
        }
        #endregion

        /// <summary>
        /// 注册 登陆账号  修改登录账号
        /// </summary>
        /// <param name="u_id">注册id</param> 
        public void _Login(int u_id)
        {
            Golf.BLL.Golf_User bll = new Golf.BLL.Golf_User();
            Golf.Model.Golf_User model = bll.GetModel(u_id);
            if (model != null)
            {
                model.LoginTime = DateTime.Now;
                bll.Update(model);
                CookiesHelper.SaveCookie("_Customer_id", Server.UrlEncode(model.Id.ToString()), 7, "D");//保存登录会员的id值
                CookiesHelper.SaveCookie("_Customer_Email", Server.UrlEncode(model.Email.ToString()), 7, "D");//保存登录会员的Email
            }
        }

        #region  确认下单 方法
        /// <summary>
        /// 获取 下单参数
        /// </summary>
        public void Get_urlMsg()
        {
            string address_id = Server.UrlDecode(Request.Form["address_id"]);
            string User_Id = Server.UrlDecode(Request.Form["User_Id"]);
            string Coupon_Code = Server.UrlDecode(Request.Form["Coupon_Code"]);//页面传入的优惠劵代码
            string Certificates_Code = Server.UrlDecode(Request.Form["Certificates_Code"]);//礼品卷代码
            string txt_Msg = Server.UrlDecode(Request.Form["txt_Msg"]);
            string txt_order = Server.UrlDecode(Request.Form["txt_order"]);

            UserId = int.Parse(User_Id);
            Golf.BLL.Golf_User u_bll = new Golf.BLL.Golf_User();
            Golf_User_Model = u_bll.GetModel(UserId);
            if (Golf_User_Model == null) { return; }
            if (Golf_User_Model.State == 0)//未注册 用户下订单
            {
                int address = int.Parse(address_id);
                Golf.BLL.Golf_Address address_bll = new Golf.BLL.Golf_Address();
                Golf.Model.Golf_Address address_model = address_bll.GetModel(address);
                if (address_model.UserId == UserId)//根据传入的送货地址 查询用户编号 进行比对
                {
                    _Email = address_model.Email;
                    AddressId = address;
                    //执行下单操作
                    order_submit(Coupon_Code, txt_Msg, Golf_User_Model.FristName, Golf_User_Model.LastName);
                }
                else
                {
                    Response.Write("没有找到信息  地址 信息为成功|");
                }
            }
            else//注册用户下单
            {
            }
        }
        /// <summary>
        /// 下单方法
        /// </summary>
        /// <param name="Coupon_Code">优惠劵代码</param>
        /// <param name="UserMessage">会员留言</param>
        protected void order_submit(string Coupon_Code, string UserMessage, string FristName, string LastName)
        {
            if (Golf_User_Model == null)
            {
                Response.Write("1|");
                return;
            }
            Golf.BLL.Golf_Order bll = new Golf.BLL.Golf_Order();
            Golf.Model.Golf_Order order = new Golf.Model.Golf_Order();

            bool IsCoupon = false;//是否优惠券	0否，1是
            decimal money = 0;
            if (Coupon_Code != "")
            {
                money = get_Coupon(Coupon_Code);
                IsCoupon = true;
            }
            else
            {
                IsCoupon = false;
            }
            string OrderNumber = Get_orderNum();//订单号 
            decimal _Coupon = money;//优惠劵金额  
            decimal OrderSumPrice = 0;//总金额

            int userid = Golf_User_Model.Id;
            string fristName = Golf_User_Model.FristName;
            string lastName = Golf_User_Model.LastName;
            decimal ProductSumPrice = Get_proSumPrice(); //产品总价

            decimal TransportationPrice = 0;//运费
            int MailTypeId = 0;//邮寄类型id	Golf_MailType表
            int IsAddPrice = 0;//是否加减金额
            string AddPriceState = "加减金额";//加减金额说明
            decimal AddPrice = 0;//增加为正数，减少为负数
            OrderSumPrice = ProductSumPrice - _Coupon - TransportationPrice + (AddPrice);
            string ProductIdList = _str1;
            string Pro_AttrList = _str4;
            DateTime OrderGeneratedTime = DateTime.Now;

            int _AddressId = AddressId;//收货地址id	Golf_Address表 
            string UserIp = ThumNail.GetIp(this.Request);//会员IP

            #region 付款字段
            int IsPayment = 0;//是否付款	0未付款，1已付款，-1已退款 
            decimal PaymentPrice = 0;//付款金额	客户付款总金额
            try
            {
                PaymentPrice = decimal.Parse(pro_price) + AddPrice;
            }
            catch (Exception)
            {
            }
            DateTime PaymentTime = DateTime.Now;//付款时间
            string PaymentOrderNumber = "DUFENG00089";//付款第三方订单号
            #endregion
            int LogisticsStateId = 0;//物流状态id	Golf_Logisticsstate表 
            int OrderStateCodeId = 0;//订单状态id
            int ProductOrderNumber = 0;//订单总件数
            foreach (var item in nums)
            {
                _sumCount += int.Parse(item);
            }
            ProductOrderNumber = _sumCount;
            bool IsDeliver = false;//是否发货	1是，0否 
            bool IsShow = true;//是否显示	1显示，0否
            order.TransportationPrice = TransportationPrice;
            order.PaymentOrderNumber = PaymentOrderNumber;
            order.LogisticsStateId = LogisticsStateId;
            order.OrderStateCodeId = OrderStateCodeId;
            order.ProductNumberList = ProductIdList;
            order.Pro_AttrList = Pro_AttrList;
            order.OrderNumber = OrderNumber;
            order.UserIp = UserIp;
            order.OrderSumPrice = OrderSumPrice;
            order.UserId = userid;
            order.FristName = fristName;
            order.LastName = lastName;
            order.ProductSumPrice = ProductSumPrice;
            order.TransportationPrice = 0;
            order.MailTypeId = MailTypeId;
            order.IsCoupon = IsCoupon;
            order.CouponPrice = money;
            order.IsAddPrice = IsAddPrice;
            order.AddPriceState = AddPriceState;
            order.AddPrice = AddPrice;
            order.ProductNumberList = ProductIdList;
            order.OrderGeneratedTime = OrderGeneratedTime;
            order.AddressId = AddressId;
            order.UserMessage = UserMessage;
            order.IsPayment = IsPayment;
            order.LogisticsStateId = 0;
            order.OrderStateCodeId = OrderStateCodeId;
            order.ProductOrderNumber = _sumCount;
            order.IsDeliver = IsDeliver; ;
            order.IsShow = IsShow;
            int or_id = bll.Add(order);
            if (or_id > 0)
            {
                Insery_orderPro(or_id, OrderNumber, FristName, LastName, userid);

                string Cart_msg = Server.UrlDecode(Request.Form["Cart_msg"]);
                PostEmail(_Email, Cart_msg);
                Response.Buffer = true;//清理缓存
                Response.ExpiresAbsolute = DateTime.Now.AddHours(-1);
                Response.Expires = 0;
                Response.CacheControl = "no-cache";
                CookiesHelper.ClearCookie("GOLF");
                Response.Write(OrderNumber + ",");
            }
            else
            {
                Response.Write("0,");
            }
        }
        /// <summary>
        ///Golf_OrderProduct (订单产品购买记录表)（订单产品表）
        /// </summary>
        /// <param name="orderid"> 订单id</param>
        /// <param name="orderNum">订单号</param>
        public void Insery_orderPro(int orderid, string orderNum, string firstname, string lastname, int userid)
        {
            string ProductIdList = "";
            ProductIdList = _str1;
            string Pro_AttrList = "";
            Pro_AttrList = _str4;
            if (ProductIdList != "" && Pro_AttrList != "")
            {
                string[] ids = ProductIdList.Split(',');
                string[] attr = Pro_AttrList.Split('|');
                for (int i = 0; i < ids.Length; i++)
                {
                    Golf.BLL.Golf_Product pro_bll = new Golf.BLL.Golf_Product();
                    Golf.Model.Golf_Product pro_model = pro_bll.GetModel(int.Parse(ids[i]));
                    if (pro_model == null)
                    {
                        continue;
                    }
                    else
                    {
                        Golf.BLL.Golf_OrderProduct order_pro = new Golf.BLL.Golf_OrderProduct();
                        Golf.Model.Golf_OrderProduct order_proModel = new Golf.Model.Golf_OrderProduct();
                        order_proModel.BuyNumber = int.Parse(nums[i]);
                        order_proModel.CreateTime = DateTime.Now;
                        order_proModel.FristName = firstname;
                        order_proModel.LastName = lastname;
                        order_proModel.OrderId = orderid;
                        order_proModel.OrderNumber = orderNum;
                        order_proModel.UserId = userid;
                        order_proModel.ProductTypeId = pro_model.Pro_TypeId;
                        order_proModel.Product_Attr = attr[i];
                        order_proModel.ProductId = pro_model.Id;
                        order_proModel.ProductName = pro_model.Pro_Name;
                        order_proModel.ProductPrice = pro_model.Pro_MarketPrice;
                        order_proModel.IsStae = 0;
                        order_pro.Add(order_proModel);
                    }
                }

            }
            else
            {
                Response.Write("0,");
            }
        }
        private static readonly object SequenceLock = new object();
        /// <summary>
        /// 订单号生产方法
        /// </summary>
        /// <returns></returns>
        public string Get_orderNum()
        {
            string returnValue = string.Empty;
            // 这里用锁的机制，提高并发控制能力
            lock (SequenceLock)
            {
                string ordernum = DateTime.Now.Ticks.ToString();
                ordernum = ordernum.Substring(ordernum.Length - 12);
                return ordernum;
            }
        }
        #endregion

        #region  获取商品总金额
        /// <summary>
        /// 获取商品总金额
        /// </summary>
        /// <returns></returns>
        public decimal Get_proSumPrice()
        {
            _str1 = null;
            _str2 = null;
            _str3 = null;
            _str4 = null;
            _key = null;
            pros = null;
            nums = null;
            _attr = null;

            decimal dSum1 = 0.00M, price1 = 0.00M;
            if (Request.Cookies["GOLF"] != null && Request.Cookies["GOLF"].ToString() != "")
            {
                HttpCookie ShopCart = Request.Cookies["GOLF"];
                _key = ShopCart.Values.AllKeys;
                CookieCount = ShopCart.Values.Count;
                for (int i = 0; i < CookieCount; i++)
                {
                    if (ShopCart.Values[i] == null || ShopCart.Values[i].Trim() == "")
                    {
                        CookieCount = 0;
                        continue;
                    }
                    else
                    {
                        string[] Products = ShopCart.Values[i].Split('|');
                        if (Products.Length > 1)
                        {
                            _str1 += Products[0] + ",";
                            _str2 += Products[1] + ",";
                            _str4 += Products[3] + "|";
                        }
                    }
                }
                if (_str1.Length > 1 & _str2.Length > 1)
                {
                    if (_str1.Substring(_str1.Length - 1, 1) == ",")
                        _str1 = _str1.Substring(0, _str1.Length - 1);
                    if (_str2.Substring(_str2.Length - 1, 1) == ",")
                        _str2 = _str2.Substring(0, _str2.Length - 1);
                    if (_str4.Substring(_str4.Length - 1, 1) == "|")
                        _str4 = _str4.Substring(0, _str4.Length - 1);

                    pros = _str1.Split(new char[] { ',' });
                    nums = _str2.Split(new char[] { ',' });
                    //构建表格
                    DataTable _page_dt = new DataTable();
                    _page_dt = bllproduct.GetList("Id in(" + _str1 + ")").Tables[0];//获取商品的详细 
                    for (int i = 0; i < _page_dt.Rows.Count; i++)
                    {
                        price1 = decimal.Parse(_page_dt.Rows[i]["Pro_Price"].ToString());
                        //循环匹配 商品
                        for (int j = 0; j < pros.Length; j++)
                        {
                            int num = int.Parse(nums[j]);
                            dSum1 += price1 * num;
                        }
                    }
                }
            }
            return dSum1;
        }
        #endregion

        #region
        public void PostEmail(string Email, string Cart_msg)
        {
            string mailSubject = "订单通知";
            string mailBody = Cart_msg;//正文内容
            string mailFrom = "dufeng_Code@163.com";
            ArrayList List = new ArrayList();
            new Golf.WebUI.App_code.SentEmail().MySendMail(Email, mailSubject, mailBody, mailFrom, List);
        }
        #endregion

    }
}
